<script setup lang="ts">
import { computed, defineAsyncComponent, onMounted, ref, shallowRef } from "vue";
import type { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import { type EnvStoreId, getEnvStore } from "@/modules/dev-env/store/factroy.ts";
import { hc } from "@/framework/vue/util/render.ts";
import {
  ArrowRightOutlined,
  CheckCircleOutlined,
  CopyOutlined,
  DeleteOutlined,
  FolderOpenOutlined,
  MoreOutlined,
  PlusOutlined,
  ReloadOutlined,
  SettingFilled,
  SettingOutlined,
} from "@ant-design/icons-vue";
import SectionCard from "@/components/app/section-card.vue";
import VTable from "@/components/framework/v-table.tsx";
import VTableColumn from "@/components/framework/v-table-column.tsx";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import { Modal } from "ant-design-vue";
import { exposeGlobalIfDev } from "@/framework/vue/util/dev-tools.ts";
import type { VTableColumnRenderArgs } from "@/components/framework/v-table-types.ts";
import { hci } from "@/components/framework/icon";
import { useToggleItemId } from "@/components/framework/toggle-view-helper.ts";
import ScrollView from "@/components/framework/scroll-view.vue";
import { copyText } from "@/util/clipboard.ts";
import { openExternal } from "@/util/shell.ts";

const InstallModal = defineAsyncComponent(() => import("./generic-env-install-modal.vue"));
const Settings = defineAsyncComponent(() => import("./generic-env-settings.vue"));

const id = useToggleItemId() as EnvStoreId;
// const id = computed<EnvStoreId>(() => "java.jdk");

const store = shallowRef<GenericEnvStore<any>>(getEnvStore(id));
const showSetting = computed(() => store.value.pageConfig?.showSetting !== false);

const installModalOpen = ref(false);
exposeGlobalIfDev("__env_store__", store);

// watch(id, () => {
//   installModalOpen.value = false;
//   if (id.value && (!store.value || id.value !== store.value.id)) {
//     store.value = getEnvStore(id.value);
//     // 没有数据时才加载数据
//     if (store.value.versionList.length === 0) {
//       store.value.loadAll();
//     }
//   }
// });

onMounted(() => {
  store.value.loadAll();
});

const handleDelete = (it: LocalVersionItem) => {
  Modal.confirm({
    centered: true,
    title: "提示",
    content: "确定要删除吗？",
    onOk: () => store.value.deleteVersion(it).then(() => store.value.loadAll()),
  });
};
</script>

<template>
  <scroll-view class="pl-10">
    <section-card :icon="store.icon" title="已安装版本">
      <div :style="{ maxHeight: '500px', minHeight: store.versionList.length === 0 ? '200px' : undefined }">
        <v-table
          row-key="installPath"
          :data-source="store.versionList"
          :loading="store.loading"
          :row-height="40"
          @row-click="store.onTableRowClick($event)"
        >
          <v-table-column width="50px" align="center">
            <template v-slot="{ record }: VTableColumnRenderArgs<LocalVersionItem>">
              <ArrowRightOutlined v-if="record === store.selectedItem" class="color-primary" />
            </template>
          </v-table-column>
          <v-table-column title="版本名称" width="280px">
            <template v-slot="{ record }: VTableColumnRenderArgs<LocalVersionItem>">
              <div :class="['w-full', record === store.selectedItem && 'bold color-primary']" @click="store.selectedItem = record">
                {{ record.displayName || record.version }}
              </div>
            </template>
          </v-table-column>
          <v-table-column data-index="installPath" title="安装路径">
            <template v-slot="{ record, value }">
              <div class="text-ellipsis pv-1" :title="value" @click="store.selectedItem = record">{{ value }}</div>
            </template>
          </v-table-column>
          <template v-for="(it, i) in store.tableColumns" :key="it.key || it.dataIndex || i">
            <v-table-column :data-index="it.dataIndex as string" :title="it.title" :width="it.width" :align="it.align" :cell-render="it.render">
              <template v-slot="rowData">
                {{ it.render ? it.render(rowData) : rowData.value }}
              </template>
            </v-table-column>
          </template>

          <v-table-column title="操作" width="100px" align="center">
            <template v-slot="{ record }: VTableColumnRenderArgs<LocalVersionItem>">
              <a-dropdown :trigger="['click']">
                <a-button type="text" :icon="hc(MoreOutlined)" />
                <template #overlay>
                  <a-menu>
                    <template v-if="store.tableActions && store.tableActions.length > 0">
                      <a-menu-item
                        v-for="it in store.tableActions"
                        :key="it.key"
                        :icon="typeof it.icon === 'string' ? hci(it.icon) : it.icon"
                        :disabled="it.disabled"
                        @click="it.onClick(record)"
                        >{{ it.name }}
                      </a-menu-item>
                      <a-menu-divider />
                    </template>
                    <a-menu-item v-if="store.pageConfig?.showCurrentAction !== false" :icon="hc(SettingOutlined)" @click="store.setDefault(record)"
                      >设为系统默认
                    </a-menu-item>
                    <a-menu-item :icon="hc(FolderOpenOutlined)" @click="openExternal(record.installPath)"> 打开安装目录</a-menu-item>
                    <a-menu-item :icon="hc(CopyOutlined)" @click="copyText(record.installPath)">复制路径</a-menu-item>
                    <a-menu-divider />
                    <a-menu-item :icon="hc(DeleteOutlined)" danger @click="handleDelete(record)">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </v-table-column>
        </v-table>
      </div>
      <template #footerLeft>
        <a-button :icon="hc(PlusOutlined)" type="primary" @click="installModalOpen = true">在线安装</a-button>
        <a-button :icon="hc(ReloadOutlined)" @click="store.loadAll()">刷新列表</a-button>
      </template>
      <template #footerRight>
        <template v-if="store.currentVersion">
          <b>{{ store.currentVersion.displayName || store.currentVersion.version }}</b>
          <CheckCircleOutlined class="color-success" />
          <span class="color-text-secondary font-12 mr-10">({{ store.currentVersion.installPath }})</span>
        </template>
      </template>
    </section-card>

    <component v-if="store.settingsComponent" :is="store.settingsComponent" :store="store" />
    <section-card v-else-if="showSetting" :icon="SettingFilled" title="设置">
      <settings :store="store" />
    </section-card>

    <install-modal v-model:open="installModalOpen" :store="store" />
  </scroll-view>
</template>

<style scoped lang="less"></style>
